import preferences from '@ohos.data.preferences';

class PreferencesUtil {
  prefMap: Map<string, preferences.Preferences> = new Map();
  // 初始化
  async loadPreferences(context, name: string) {
    try {
      let pref = await preferences.getPreferences(context, name)
      this.prefMap.set(name, pref);
      //console.log('preferencesTag', `加载Preferences[${name}]成功`);
    } catch (e) {
      //console.log('preferencesTag', `加载Preferences[${name}]失败`, JSON.stringify(e));

    }
  }
  // 添加数据
  async putPreferences(name: string, key: string, value: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      //console.log('preferencesTag', `putPreferences[${name}]尚未初始化`)
      return
    }
    try{
      let pref = this.prefMap.get(name);
      // 写入数据
      await pref.put(key, value);
      // 刷盘写入数据
      await pref.flush();
      //console.log('preferencesTag', `putPreferences[${name}]成功`);
    }catch (err){
      //console.log('preferencesTag', `putPreferences[${name}]失败`);
    }
  }
  // 获取数据
  async getPreferences(name: string, key: string, value: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      //console.log('preferencesTag', `putPreferences[${name}]尚未初始化`)
      return undefined
    }
    try{
      let pref = this.prefMap.get(name);
      // 读取数据
      let res = await pref.get(key, value)
      //console.log('preferencesTag', `getPreferences[${name}.${key}]=${value}]成功`);
      return res
    }catch (err){
     // console.log('preferencesTag', `getPreferences[${name}.${key}]失败`, JSON.stringify(err));
    }
  }
  // 删除数据，调用dataPreferences的deletePreferences接口
  async deletePreferences(name: string, key: string, defaultValue: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      //console.log('preferencesTag', `putPreferences[${name}]尚未初始化`)
      return
    }
    try{
      let pref = this.prefMap.get(name);
      await pref.delete(key)
      //console.log('preferencesTag', `deletedPreferences[${name}.${key}]成功`);
    }catch (err){
     // console.log('preferencesTag', `deletedPreferences[${name}.${key}]失败`, JSON.stringify(err));
    }
  }
}

const preferencesUtil = new PreferencesUtil();
export default preferencesUtil as PreferencesUtil;